﻿// Copyright (c) 2025 liucl
// Inject is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan
// PSL v2.
// You may obtain a copy of Mulan PSL v2 at:
//          http://license.coscl.org.cn/MulanPSL2
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
// See the Mulan PSL v2 for more details.

#include "dialog.hpp"
#include "contrl/log.hpp"
#include "contrl/process.hpp"
#include "core/injector.hpp"

enum { ID_TREE = wxID_HIGHEST + 10000, ID_LOG };
enum { LOG_DIALOG = 0, PROCESS_DIALOG = 1 };
Dialog::Dialog(wxWindow *parent)
    : wxDialog(parent, wxID_ANY, "Inject", wxDefaultPosition, wxSize(800, 600),
               wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER) {
  auto sizer = new wxBoxSizer(wxVERTICAL);
  auto processControl = new ProcessControl(this, ID_TREE);
  sizer->Add(processControl, 1, wxEXPAND);
  SetSizer(sizer);
  switchUI(PROCESS_DIALOG);
}
Dialog::~Dialog() {}
void Dialog::OnClose(wxCloseEvent &event) { Destroy(); }
void Dialog::OnInject(wxCommandEvent &event) {
  DWORD pid = static_cast<DWORD>(event.GetExtraLong());
  // 选择一个模块用于注入
  auto module = wxFileSelector(
      wxASCII_STR(wxFileSelectorPromptStr), wxEmptyString, wxEmptyString,
      wxEmptyString, wxT("DLL files (*.dll)|*.dll|All files (*.*)|*.*"),
      wxFD_FILE_MUST_EXIST, this);
  if (module.IsEmpty()) {
    return;
  }
  //  注入
  if (Injector::Inject(pid, module.ToStdWstring())) {
    pid_ = pid;
    module_ = module;
    wxMessageBox(wxT("注入成功"), wxT("提示"), wxOK | wxICON_INFORMATION);
    switchUI(LOG_DIALOG);
  } else {
    wxMessageBox(wxT("注入失败"), wxT("提示"), wxOK | wxICON_ERROR);
  }
}
void Dialog::OnUninject(wxCommandEvent &event) {
  if (Injector::UnInject(pid_, module_.ToStdWstring())) {
    wxMessageBox(wxT("卸载成功"), wxT("提示"), wxOK | wxICON_INFORMATION);
  } else {
    wxMessageBox(wxT("卸载失败"), wxT("提示"), wxOK | wxICON_ERROR);
  }
  switchUI(PROCESS_DIALOG);
}
void Dialog::switchUI(int ui) {

  // 清除Sizer中的旧控件
  auto sizer = GetSizer();
  if (sizer) {
    sizer->Clear(true);
  } else {
    sizer = new wxBoxSizer(wxVERTICAL);
    SetSizer(sizer);
  }
  wxWindow *ctrl = nullptr;
  if (ui == LOG_DIALOG) {
    ctrl = new LogControl(this, ID_LOG);
  } else if (ui == PROCESS_DIALOG) {
    ctrl = new ProcessControl(this, ID_TREE);
  }
  if (ctrl == nullptr) {
    return;
  }

  sizer->Add(ctrl, 1, wxEXPAND);
  Layout();
}
// clang-format off
wxBEGIN_EVENT_TABLE(Dialog, wxDialog) 
    EVT_CLOSE(Dialog::OnClose)
    EVT_COMMAND(ID_TREE,EVT_EVENT_INJECT, Dialog::OnInject)
    EVT_COMMAND(wxID_ANY,EVT_EVENT_UNINJECT, Dialog::OnUninject)
wxEND_EVENT_TABLE()
    // clang-format on
